#!/usr/bin/python
#
# manager.py for neu-oj
# needn't sudo
# Copyright (C) 2011-2011 NEU-OJ Project
# Author: Philo Yang <ud1937@gmail.com>
# URL: <http://yangzhe1991.org/>
# For license information, see LICENSE.txt
import socket
import struct
import thread
import threading
import time

global waiting
global running
global key
key='fuckgre'
#should be same to each judger
waiting=[]
running=[]

def recvsubmit(jiong):
	HOST = ''  
	PORT = 12345      
	s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	s.bind((HOST, PORT))
	while 1:
		#print s.accept()
		#print 'Connected by', addr
		data,(addr,port) = s.recvfrom(66666)
		#print data
		waiting.append(data)
		#print 'append',data
	s.close()

def checkrunning(jiong):
	while 1:
		time.sleep(5)
		#print waiting
def recvjudger(jiong):
	HOST  = ''
	PORT = 23456     
	s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	s.bind((HOST, PORT))
	while 1:
		#print s.accept()
		data,(addr,port) = s.recvfrom(66666)
		#print 'Connected by', addr
		#print data
		if data==key+'can judge':
			ll=len(waiting)
			#print ll
			if(ll>0):
				data=waiting.pop()
				s.sendto(key+data,(addr,port))
				#print 'pop',data
			else:
				s.sendto(key+'sb',(addr,port))
				pass
	s.close()

if __name__=='__main__':
	t1=threading.Thread(target=recvsubmit, args=(10,))
	#thread.start_new_thread(checkrunning,(1,))
	t3=threading.Thread(target=recvjudger, args=(10,))
	t1.start()
	t3.start()
	t1.join()
	t3.join()	
